<script lang="ts" setup>
import { get, post, Message, loadFile, message } from '@/utils'
import { isEmpty } from 'lodash'
type Emits = {
  success: [img: string]
  'update:list': [list: string[]]
  remove: [index: number]
  fail: []
  file: any
  'update:value': [string]
}
const props = withDefaults(
  defineProps<{
    separator?: string //切割标识
    list: any[] | string //文件列表|需要根据标识切割的字符串
    preview?: boolean //开启图片预览
    accept?: string //上传文件类型
    disabled?: boolean //禁用
    multiple?: boolean //多文件上传
    tip?: string
    value?: string
    limit?: number //上传数量
    showRemoveBtn?: boolean //显示删除按钮
    showBtn?: boolean //是否显示上传按钮
    listType?: 'text' | 'picture' | 'picture-card' //图片列表类型
    api?: string
    fileName?: string
    notUpload?: boolean
    showFileList?: boolean
    categoryId: any //文件归属分类ID
    formDataFileKey?: string
    formData?: any //自定义接口接收的formdata
  }>(),
  {
    notUpload: false,
    preview: true,
    disabled: false,
    multiple: false,
    accept: '.jpg,.JPG,.JPEG,.jpeg,.png,.PNG,.mp4,.MP4,.mp3,.MP3',
    limit: 0,
    showRemoveBtn: true,
    showBtn: true,
    showFileList: true,
    separator: ',',
    listType: 'picture-card',
    formDataFileKey: 'file',
    api: '/server-resource/oss/endpoint/put/file',
  }
)

const valStr = ref('')
const emit = defineEmits<Emits>()
const fileList = ref<any[]>([])
/**等待上传的图片 */
const waitUploadList = ref<any[]>([])
/**上传图片 */
const customRequest = option => {
  const { onProgress, onSuccess, fileItem, name } = option
  waitUploadList.value.push(fileItem.file)
  onProgress(100)
  onSuccess()
  if (!isEmpty(props.formData)) {
    onUpload(fileItem.file)
  }
  return {
    abort() {},
  }
}
const onUpload = item => {
  return new Promise((resolve, reject) => {
    const formData = new FormData()
    if (props.formData) {
      Object.keys(props.formData).forEach(key => {
        formData.append(key, props.formData[key])
      })
    }
    formData.append(props.formDataFileKey, item)
    post(
      {
        url: props.api + '?categoryId=' + props.categoryId,
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryMBKIj1uGXeRNivgf',
        },
      },
      ({ data }) => {
        console.log(data)
        const list = valStr.value.split(',').filter(Boolean)
        if (props.formData) {
          list.push(data.mediaId || data.link)
          valStr.value = list.join(',')
          emit('update:value', valStr.value)
        } else {
          list.push(data.link)
          valStr.value = list.join(',')
        }
        resolve({})
      },
      ({ msg }) => {
        message({
          content: msg || '上传失败',
          type: 'error',
        })
      }
    )
  })
}
/**删除 */
const onRemove = (fileItem): any => {
  return new Promise((resolve, reject) => {
    const _index = fileList.value.findIndex(f => f.url == fileItem.url)
    console.log(_index)
    if (_index != -1) {
      emit('remove', _index)
      // fileList.value.splice(_index, 1);
      const list = valStr.value.split(',').filter(Boolean)
      list.splice(_index, 1)
      valStr.value = list.join(',')
      emit('update:value', valStr.value)
      waitUploadList.value.splice(_index, 1)
      resolve(true)
    } else reject(false)
  })
}
const initImg = img => {
  fileList.value = []
  if (img && typeof img === 'string') {
    img
      .split(props.separator)
      .filter(Boolean)
      .forEach((item, i) => {
        fileList.value.push({
          url: item,
          name: (props.fileName ?? '') + '文件' + (i + 1),
        })
      })
    valStr.value = props.list as string
  } else {
    if (!img?.length) return
    ;(img as any[]).map((v, i) => {
      fileList.value.push({
        url: v,
        name: (props.fileName ?? '') + (i + 1),
      })
    })
  }
}
/**监听重置fileList */
watch(
  () => props.list,
  newVal => {
    initImg(newVal)
  }
)
onMounted(() => {
  initImg(props.list)
})
defineExpose({
  onUpload(cb) {
    const requstList: Promise<any>[] = []
    waitUploadList.value.forEach(item => {
      requstList.push(onUpload(item))
    })
    console.log(requstList)
    // cb(false)
    // return
    Promise.all(requstList)
      .then(() => {
        emit('update:value', valStr.value)
        cb(true)
      })
      .catch(() => cb(false))
  },
})
</script>
<template>
  <a-upload
    :list-type="props.listType"
    action="/"
    :limit="props.limit"
    v-model:file-list="fileList"
    :image-preview="props.preview"
    :disabled="props.disabled"
    :multiple="props.multiple"
    :showFileList="props.showFileList"
    :show-remove-button="props.showRemoveBtn"
    :tip="props.tip"
    :show-upload-button="props.showBtn"
    :accept="props.accept"
    :custom-request="customRequest"
    @before-remove="fileItem => onRemove(fileItem)"
  />
</template>
<style lang="less" scoped></style>
